﻿// ui functions
$(document).ready(function () {
    registerProgressIndication();

    registerResetMe();

    dualBoxInit();

    registerCommomDeleting();

    gridInit();

    boxExpandCollapse();

    folderSwitchView();

    fileUploadInit();

    fileViewDialog();

    categoryInit();

    toggleTooltip();

    propertyInit();

    changeBlockInit();

    pagePreviewInit();

    pageAnnotationInit();

    templatePreviewInit();

    modulePreviewInit();

    pageTemplateRegionInit();

    emulateTextDisabled();

    telerikEditorViewSource();

    mediaContentInit();

    contentCategoryInit();

    registerAddingNewItem();

    registerAjaxLink();

    selectInputControl();

    registerShowHide();

    registerSwitchSite();

    initContentPicker();

    workflowDashboardInit();

    initCmsPager();

    searchSnippetInit();

    registerPageEdit();

    initMetas();

    initPagesFilter();

    initCommonFancyBox();

    initSetPassword();

    initConfirm();

    initMediaPicker();

    window.setInterval('initReconnect()', 600000); //1000ms * 60s * 10m
});

function initMediaPicker() {
    var mediapickerTimer;

    function openMediaPickerDialog(url, $btn) {
        var data = {
            elementId: $btn.data("element-id"),
            mediaTypes: $btn.data("media-types")
        };
        $.fancybox({
            'href': url,
            'titlePosition': 'inside',
            'transitionIn': 'none',
            'transitionOut': 'none',
            'autoDimensions': false,
            'ajax': {
                type: 'POST',
                data: data
            },

            'width': 650,
            'height': 300
        });
    }

    $(".js-mediapicker-browse-btn").click(function (e) {
        e.preventDefault();
        openMediaPickerDialog($.cmsAdminOptions.options.knownUrls.mediaPickerBrowseUrl, $(this));
    });

    $(".js-mediapicker-select-btn").click(function (e) {
        e.preventDefault();
        openMediaPickerDialog($.cmsAdminOptions.options.knownUrls.mediaPickerUrl, $(this));
    });

    $(".js-mediapicker-remove").click(function (e) {
        e.preventDefault();

        if (!confirm(window.adminResources.media.deattachWarning)) {
            return;
        }

        var $element = $(this);
        var $container = $element.closest(".js-mediapicker-container");
        var elementId = $element.attr("data-element-id");
        $("#" + elementId).val('');
        $container.find(".js-mediapicker-remove").hide();
        $container.find(".js-mediapicker-img").hide();
        $container.find(".js-mediapicker-content-title").val('');
    });

    $(".js-mediapicker-folder").live("click", function (e) {
        e.preventDefault();

        var folderId = $(this).data("folder-id");
        var $searchBox = $("#js-mediapicker-searchbox");
        var mediaTypes = $("#hiddenMediaTypes").val();
        $(".js-mediapicker-folder").removeClass("b-current");
        $(this).addClass("b-current");
        $("#js-mediapicker-searchbox").attr("data-folder-id", folderId);
        loadMediaContent($.cmsAdminOptions.options.knownUrls.mediaPickerLoadUrl, { mediaId: folderId, keyword: $searchBox.val(), mediaTypes: mediaTypes ? mediaTypes : undefined });
    });

    $(".js-mediapicker-content-item").live("click", function (e) {
        e.preventDefault();

        var $mediaContent = $(this);
        var $okBtn = $("#js-mediapicker-ok-btn");

        $(".js-mediapicker-content-item").removeClass("b-current");
        $mediaContent.addClass("b-current");
        $okBtn.attr("data-content-id", $mediaContent.attr("data-content-id"));
        $okBtn.attr("data-linked-file", $mediaContent.attr("data-linked-file"));
        $okBtn.attr("data-content-title", $mediaContent.text());
    });

    $("#js-mediapicker-searchbox").live("keypress", function () {
        var $searchBox = $("#js-mediapicker-searchbox");
        var mediaTypes = $("#hiddenMediaTypes").val();
        clearTimeout(mediapickerTimer);
        mediapickerTimer = setTimeout(function () {
            loadMediaContent($.cmsAdminOptions.options.knownUrls.mediaPickerLoadUrl, { mediaId: $searchBox.attr('data-folder-id'), keyword: $searchBox.val(), mediaTypes: mediaTypes ? mediaTypes : undefined });
        }, 500);
    });

    $("#js-mediapicker-close-btn").live("click", function (e) {
        $.fancybox.close();
    });

    function setMediaContentAndCloseDialog(elementId, contentId, contentTitle, linkedFile) {
        if (contentId > 0) {
            var $element = $("#" + elementId);
            var $container = $element.closest(".js-mediapicker-container");

            $container.find(".js-mediapicker-remove").show();
            if ($container.find(".js-mediapicker-img").length) {
                var img = $container.find(".js-mediapicker-img");
                img.show().attr('src', '/admin/media/' + linkedFile + '?' + img.attr('src').split('?')[1]);
            }
            $container.find(".js-mediapicker-content-title").val(contentTitle);
            $element.val(contentId);

            $.fancybox.close();
        }
    }

    $("#js-mediapicker-ok-btn").live("click", function (e) {
        e.preventDefault();

        var $okBtn = $(this);
        var elementId = $okBtn.attr("data-element-id");
        var contentId = $okBtn.attr("data-content-id");
        var contentTitle = $okBtn.attr("data-content-title");
        var linkedFile = $okBtn.attr("data-linked-file");

        setMediaContentAndCloseDialog(elementId, contentId, contentTitle, linkedFile);
    });

    $("#js-mediapicker-upload-btn").live("click", function (e) {
        e.preventDefault();
        var mediaId = $("#js-mediapicker-folders").find(":selected").val();
        var $uploadBtn = $(this);

        mediaPickerRequest(
            $.cmsAdminOptions.options.knownUrls.mediaPickerSaveMediaContentUrl,
            { mediaId: mediaId, fileId: $uploadBtn.attr("data-media-file-id") },
            function (data) {
                if (data && data.IsMediaSaved) {
                    setMediaContentAndCloseDialog($uploadBtn.attr("data-element-id"), data.MediaContentId, $uploadBtn.attr("data-content-title"), data.LinkedFile);
                }
            },
            function (data) {
                alert('Error');
                $.fancybox.close();
            });
    });

    $("#js-mediapicker-clear-search").live("click", function (e) {
        var $searchBox = $("#js-mediapicker-searchbox");
        $searchBox.val('');
        loadMediaContent($.cmsAdminOptions.options.knownUrls.mediaPickerLoadUrl, { mediaId: $searchBox.attr('data-folder-id') });
    });

    function loadMediaContent(url, data) {
        mediaPickerRequest(
            url,
            data,
            function (e) {
                $("#js-mediapicker-content").replaceWith(e);
            }, function (e) {
                $("#js-mediapicker-content").html('Error. Something went wrong.');
            });
    }

    function mediaPickerRequest(url, data, successCallback, errorCallback) {
        $.ajax({
            url: url,
            async: true,
            cache: false,
            type: "POST",
            data: data
        }).success(function (e) {
            if (successCallback) {
                successCallback(e);
            }
        }).error(function (e) {
            if (errorCallback) {
                errorCallback(e);
            }
        });
    }
}

function onMediapickerFileUploadSuccess(e) {
    var $uploadBtn = $("#js-mediapicker-upload-btn");

    if (e.response && e.response.IsFileUploaded) {
        $uploadBtn.attr("data-media-file-id", e.response.FileId);
        $uploadBtn.attr("data-content-title", e.files[0].name);
        $uploadBtn.removeAttr("disabled");
    } else {
        $uploadBtn.attr("disabled", "disabled");
    }
}

function onMediapickerFileUploaded(e) {
    e.data = { 'name': e.files[0].name };
}

function initConfirm() {
    $(".js-confirm").click(function (e) {
        if (!confirm($(this).data("message"))) {
            e.preventDefault();
        }
    });
}

function initCmsPager() {
    $(".js-cms-pager-link").live("click", function (e) {
        e.preventDefault();
        var $el = $(this);
        var mediaTypes = $("#hiddenMediaTypes").val();
        var par = { page: $el.data("page"), size: $el.data("size"), isInAjax: true, mediaTypes: mediaTypes ? mediaTypes : undefined };

        $.extend(par, $el.serializeFromData("data-pager-"));

        $.post($el.data("url"), par, function (data) {
            var container = $el.data("container");
            $(container).replaceWith(data);
            $(".js-cms-pager-link").removeClass("b-current");
            $(".js-cms-pager-link-" + $el.data("page")).addClass("b-current");
        });
    });
}

function initContentPicker() {
    var items = new Array();
    $("#Types").live("change", function () {
        var $el = $(this);
        $(".js-item-preview").html("");
        $.post($.cmsAdminOptions.options.knownUrls.contentItemsUrl, { id: $el.val() }, function (data) {
            var $items = $("#Items");
            $items.find("option").remove();
            items = new Array();
            for (var i = 0; i < data.length; i++) {
                $items.append("<option value=\"" + data[i].Id + "\">" + data[i].ContentTitle + "</option>");
                items[data[i].Id] = data[i].ContentBody;
            }
        });
    });

    $("#Items").live("change", function () {
        $(".js-item-preview").html("<h2>Snippet Preview</h2>" + items[$(this).val()[0]]);
    });

    $(".js-select-snippet").live("click", function (e) {
        e.preventDefault();
        var val = $("#Items").val();
        $.fancybox.close();
        $(document).trigger("contentSelected", [val]);
    });
}

function selectInputControl() {
    var $metaFieldType = $("#MetaFieldType");
    var $editorName = $("#EditorName");
    var $selectedInputControl = $("#SelectedInputControl");

    var setData = function ($el) {
        var systemType = $el.data("system-type");
        var partialView = $el.data("partial-view");

        if ($el.val() == 0) {
            $editorName.closest('li').removeClass('hide');
        } else {
            $editorName.closest('li').addClass('hide');
        }
        $metaFieldType.val(systemType);
        $editorName.val(partialView);
    };

    var getElement = function ($el) {
        return $selectedInputControl.find("option[data-partial-view=" + $el.val() + "]").attr("selected", "selected");
    };
    setData(getElement($editorName));
    $("#SelectedInputControl").change(function () {
        setData($(this).find("option:selected"));
    });
}

function registerShowHide() {
    $(".js-checkbox-show-hide").each(function () {
        var $el = $(this);
        var $div = $($el.data("container"));
        if ($el.is(":checked")) {
            $div.show();
        }
        else {
            $div.hide();
        }
    }).live("change", function () {
        var $el = $(this);
        var $div = $($el.data("container"));
        if ($el.is(":checked")) {
            $div.show();
        }
        else {
            $div.hide();
            $div.find("input:text").val("");
        }
    });

    $(".js-select-show-hide").each(function () {
        var $el = $(this);
        var pref = $el.data("prefix");
        if (!pref) {
            pref = "";
        }
        var $div = $($el.data("container"));
        $div.hide();
        $(".js-" + pref + $el.val().toLowerCase()).show();
    }).live("change", function () {
        var $el = $(this);
        var pref = $el.data("prefix");
        if (!pref) {
            pref = "";
        }
        var $div = $($el.data("container"));
        $div.hide();
        $(".js-" + pref + $el.val().toLowerCase()).show();
    });
}

function registerAjaxLink() {
    $(".js-ajax-link").live("click", function (e) {
        e.preventDefault();
        var $el = $(this);

        if ($el.data("confirm-message") && !confirm($el.data("confirm-message"))) {
            return;
        }

        $.post($el.attr("href"), function (data) {
            var $replaceContainer = $($el.data("container"));
            if ($replaceContainer && $replaceContainer.length > 0) {
                $replaceContainer.replaceWith(data);
            }
        });
    });
}

function registerAddingNewItem() {
    $(".js-add-more-item").live("click", function (e) {
        e.preventDefault();
        var $el = $(this);
        var $container = $($el.data("container"));
        var $ol = $el.closest("ol");
        var index = $ol.find("ol li").length;
        var newItem = '<li class="b-form__row g-clear js-item js-first-item">' +
            '<div class="b-form__row__inner"><label for="">' + window.adminResources.metas.label + '</label><br><input type="text" value="" name="Values[' + index + '].Value" id="Values_' + index + '__Value" class="text valid"></div>' +
            '<div class="b-form__row__inner"><label for="">' + window.adminResources.metas.key + '</label><br><input type="text" value="" name="Values[' + index + '].Key" id="Values_' + index + '__Key" class="text"></div>' +
            '<div class="b-form__row__inner"><label for="">' + window.adminResources.metas.selected + '</label><br><input type="checkbox" value="true" name="Values[' + index + '].Selected" id="Values_' + index + '__Selected" class="js-selected-checkbox"><input type="hidden" value="false" name="Values[' + index + '].Selected"></div>' +
            '</li>';
        $container.find(".b-form__rows_properties").append($(newItem));
    });
}

function registerProgressIndication() {
    var $el = $('.b-loading').css({
        'background-color': '#fff',
        'opacity': 0.5,
        'cursor': 'auto',
        'height': $(document).height()
    });
    $.ajaxSetup({
        cache: false
    });
    if ($el) {
        $el.ajaxStart(function () {
            $(this).fadeIn();
        })
        .ajaxComplete(function () {
            $(this).fadeOut();
        })
        .ajaxError(function (e, jqxhr) {
            viewModel.viewEventModel.addEvent({ eventTitle: jqxhr.statusText, eventBody: jqxhr.responseText })
            e.preventDefault();
        });
    }
}

function registerResetMe(selector) {
    var selector = '.reset-me-' + selector;
    $(selector).each(function () {
        var $el = $(this);
        if ($el.is('select')) {
            $el[0].selectedIndex = 0;
        } else if ($el.is("input:text")) {
            $el.val("");
        }
    });
}

function togglePair(selectorToHide, selectorToShow) {
    $(selectorToHide).addClass("hide");
    $(selectorToShow).removeClass("hide");
}

//dual listbox functions
function selectIndexAfterMove(container, index) {
    if ((container.length > index) && (index != -1)) {
        container.selectedIndex = index;
    }
}

function dualBoxInit() {
    $('fieldset.b-dual-list #btnAdd').live('click', function () {
        var movedElementIndex = $(":input.available-items option:selected").index();
        $(":input.available-items option:selected").appendTo(":input.selected-items");
        selectIndexAfterMove($(":input.available-items")[0], movedElementIndex);
    });
    $(':input.available-items').live('dblclick', function () {
        var movedElementIndex = $(":input.available-items option:selected").index();
        $(":input.available-items option:selected").appendTo(":input.selected-items");
        selectIndexAfterMove($(":input.available-items")[0], movedElementIndex);
    });
    $('fieldset.b-dual-list #btnAddAll').live('click', function () {
        $(":input.available-items option").appendTo(":input.selected-items");
    });
    $('fieldset.b-dual-list #btnRemove').live('click', function () {
        var movedElementIndex = $(":input.selected-items option:selected").index();
        $(":input.selected-items option:selected").appendTo(":input.available-items");
        selectIndexAfterMove($(":input.selected-items")[0], movedElementIndex);
    });
    $(':input.selected-items').live('dblclick', function () {
        var movedElementIndex = $(":input.selected-items option:selected").index();
        $(":input.selected-items option:selected").appendTo(":input.available-items");
        selectIndexAfterMove($(":input.selected-items")[0], movedElementIndex);
    });
    $('fieldset.b-dual-list #btnRemoveAll').live('click', function () {
        $(":input.selected-items option").appendTo(":input.available-items");
    });
}

function registerCommomDeleting() {
    $('a.b-entity-delete-pagecontrol').live("click", function () {
        var $el = $(this);
        var $elTitle = $el.attr('title');
        var message = $el.data("confirm-message");
        if (message == null || message == 'undefined' || message == '') {
            message = "Are you sure you want to delete this " + $elTitle + "?";
        }
        if (confirm(message)) {
            $.ajax({
                type: 'DELETE',
                url: $el.attr('href'),
                success: function (data) {
                    if (data.success == 1) {
                        var pageControlId = '.page-control-' + $el.attr('rel');
                        $(pageControlId).remove();
                        changePageControlAreaState(data.total == 0, $('#pageControls'), true);
                    }
                },
                dataType: 'json'
            });
        }
        return false;
    });
}

function deleteMethod(selector, callback) {
    $(selector).live("click", function () {
        var $el = $(this);
        var $elTitle = $el.attr('title');
        var confirmMessage = "Are you sure you want to delete this " + $elTitle + "?";
        if ($el.data("confirm-message") != null) {
            confirmMessage = $el.data("confirm-message");
        }
        if (confirm(confirmMessage)) {
            var urlParts = $el.attr('href').split('/');
            var url = "";
            var id;
            var index = 0;
            var i = urlParts.length;
            while (i--) {
                if (index == 0) {
                    id = urlParts[i];
                }
                else if (index > 1) {
                    url = urlParts[i] + '/' + url;
                }
                index++;
            }
            url = url + "deleteajax/" + id;
            $.ajax({
                type: 'DELETE',
                url: url,
                success: function (data) {
                    if (data == 1) {
                        if (callback) {
                            callback($el);
                        }
                    }
                },
                dataType: 'json'
            });
        }
        return false;
    });
}

//grid functions
function gridInit() {
    $("#pageSize").change(function () {
        $(this).closest("form").submit();
    });

    //highlight grid rows on mouseover
    $('.t-grid table tr').live('mouseover mouseout', function (event) {
        if (event.type == 'mouseover') {
            $(this).addClass("b-highlight");
        } else {
            $(this).removeClass("b-highlight");
        }
    });

    //delete item
    deleteMethod(".b-icon_delete", function ($el) {
        if ($el) {
            var type = $el.attr('Title');
            if (type) {
                window.location.href = window.location.href;
            }
            else {
                $(".t-refresh").click();
            }
        }
        else {
            $(".t-refresh").click();
        }
    });
}

//Switch the "Open" and "Close" state per click
function boxExpandCollapse() {
    $(".b-icon_expand").live('click', function () {
        var $el = $(this);
        if ($el.hasClass('b-icon_slider')) {
            //slider
            $el.toggleClass("b-icon_expand_max").toggleClass("b-icon_expand_min");
            $el.parent(".b-form__head").next(".b-form__body").slideToggle("fast", function () {
                if ($(this).parents().hasClass('masonry-brick')) {
                    $container.masonry('reload');
                }
            });
            $('.b-icon_slider').each(function () {
                var $anotherEl = $(this);
                if ($el.attr('id') != $anotherEl.attr('id')) {
                    if ($anotherEl.hasClass("b-icon_expand_min")) {
                        $anotherEl.toggleClass("b-icon_expand_max").toggleClass("b-icon_expand_min");
                        $anotherEl.parent(".b-form__head").next(".b-form__body").slideToggle("fast");
                    }
                }
            });
        }
        else {
            $el.toggleClass("b-icon_expand_max").toggleClass("b-icon_expand_min");
            PubSub.publish(
                $.cmsAdminEvents.registeredEvents.ShowHideChildren,
                new cmsAdminExpandItem(
                    $el.hasClass("b-icon_expand_max"),
                    $el.attr('href'),
                    $el.attr('rel'),
                    $el.attr('rev'),
                    $el.parents('tr')));
            $el.parent(".b-form__head").next(".b-form__body").slideToggle("fast");
        }
        return false;
    });
}

//Folder switcher
function folderSwitchView() {
    $(".b-switch_thumb").toggle(function () {
        $(this).removeClass("b-switch_thumb_swap");
        $(".switch_display").fadeOut("fast", function () {
            $(this).fadeIn("fast").addClass("b-media_wide");
        });
    }, function () {
        $(this).addClass("b-switch_thumb_swap");
        $(".switch_display").fadeOut("fast", function () {
            $(this).fadeIn("fast").removeClass("b-media_wide");
        });
    });
}

//File upload
function fileUploadInit() {
    $("#file_uploader")
        .text("You browser doesn't support file uploader component. Please upgrade your browser.")
        .pluploadQueue({
        // General settings
        runtimes: $.cmsAdminOptions.options.fileUploaderOptions.supportedRuntimes,
        flash_swf_url: $.cmsAdminOptions.options.fileUploaderOptions.flashHandlerUrl,
        silverlight_xap_url: $.cmsAdminOptions.options.fileUploaderOptions.silverlightHandlerUrl,
        url: $.cmsAdminOptions.options.fileUploaderOptions.uploadUrl,
        max_file_size: $.cmsAdminOptions.options.fileUploaderOptions.maxFileSize,
        chunk_size: $.cmsAdminOptions.options.fileUploaderOptions.chunkSize,
        unique_names: false,

        // Specify what files to browse for
        filters: [
			{ title: "Image files", extensions: $.cmsAdminOptions.options.fileUploaderOptions.imageTypeExtensions },
            { title: "Document files", extensions: $.cmsAdminOptions.options.fileUploaderOptions.docTypeExtensions },
            { title: "Video files", extensions: $.cmsAdminOptions.options.fileUploaderOptions.videoTypeExtensions },
			{ title: "Archive files", extensions: $.cmsAdminOptions.options.fileUploaderOptions.archiveTypeExtensions }
        ],

        //events
        init: {
            FileUploaded: function (up, file, info) {
                var tmp = document.createElement("div");
                tmp.innerHTML = info.response;
                var response = tmp.textContent || tmp.innerText;
                var infoObj = $.parseJSON(response);
                if (infoObj) {
                    if (infoObj.IsFileUploaded) {
                        viewModel.mediaFileModel.uploadedFile(
                            new mediaFile(file.name, infoObj.FileId, GetUploadedFilePreviewLink(infoObj.IsImage, infoObj.LinkedFileName, infoObj.FileType)));
                    }
                }
            },
            UploadComplete: function (up) {
                var $tabStrip = $("#UploadMediaContent").data("tTabStrip");
                if ($tabStrip) {
                    var item = $("li", $tabStrip.element)[1];
                    $tabStrip.enable(item);
                    $tabStrip.select(item);
                    item = $("li", $tabStrip.element)[0];
                    $tabStrip.disable(item);
                    $('.mediaContentTag').chosen();
                }
            },
            Error: function (up, args) {
                viewModel.viewEventModel.addEvent({ eventTitle: ConvertUploadStatus(args.file.status), eventBody: args.message + ' for ' + args.file.name });
                up.destroy();
                fileUploadInit();
            }
        }
    });
    $('#btnMediaContentUpload').live('click', function () {
        $el = $('#AllMedia');
        if ($el) {
            var mediaFolderId = $el.val();
            if (mediaFolderId == 0) {
                //show create dialog
                $.fancybox({
                    'href': $.cmsAdminOptions.options.knownUrls.newMediaFolderUrl,
                    'titlePosition': 'inside',
                    'transitionIn': 'none',
                    'transitionOut': 'none'
                });
            }
            else {
                //send media to server
                viewModel.mediaFileModel.toServer(mediaFolderId, function (result, url) {
                    if (result == 1) {
                        window.location.href = url;
                    }
                    else {
                        viewModel.viewEventModel.addEvent({ eventTitle: 'Error in file(s) processing', eventBody: result });
                    }
                });
            }
        }
        return false;
    });
    $('#fancybox-wrap :submit').live('click', function () {
        var $elContainer = $('#selectMediaFolderContainer');
        if ($elContainer && $elContainer.is('div')) {
            $.post($.cmsAdminOptions.options.knownUrls.createNewMediaFolderUrl, $('#addNewMediaFolder').serializeArray())
                .success(function (data) {
                    $elContainer.html(data);
                    parent.$.fancybox.close();
                })
                .error(function () {
                    parent.$.fancybox.close();
                });
        }
        return false;
    });
}
function ConvertUploadStatus(status) {
    var value;
    // Convert status to human readable
    switch (status) {
        case plupload.FAILED:
            value = 'Upload file failed';
            break;
        case plupload.DONE:
            value = 'Upload file done';
            break;
        default:
            value = 'Unspecified';
    }
    return value;
}
function GetUploadedFilePreviewLink(isImage, fileName, fileType) {
    if (isImage) {
        fileName = $.cmsAdminOptions.options.knownUrls.previewMediaUrl + '/' +
            fileName + '?w=' +
            $.cmsAdminOptions.options.fileViewOpions.uploadPreviewWidth + '&h=' +
            $.cmsAdminOptions.options.fileViewOpions.uploadPreviewHeight;
    }
    else {
        fileName = $.cmsAdminOptions.options.knownUrls.mediaPreviewPath + '/' + fileType + '.png';
    }
    return fileName;
}

//File view dialog
function fileViewDialog() {
    var fileViewDialogJobSignaller = {};
    $('.showFileDialog').live('click', function () {
        var $el = $(this);
        var usedClass = $el.attr('class');
        var pageId = $el.data('pageId');
        var elId = $el.attr('id');
        var targetId = $el.val();
        var containerId = elId + '_container';
        var $elContainer = $('#' + containerId);
        var isLoaded = fileViewDialogJobSignaller[elId];
        var url = getFileDialogLoadUrl(usedClass) + (pageId !== undefined ? "?id=" + pageId : "");

        if (!isLoaded) {
            $.post(url, function (data) {
                $elContainer.html(data);
                $elContainer.show();
                $elContainer.children('.hideFileDialog').toggleClass('hide');
                fileViewDialogJobSignaller[elId] = true;
            });
        }
        else {
            $elContainer.show();
            var $hideFileDialog = $(this).next('div#' + elId + '_container').children('.hideFileDialog');
            if ($hideFileDialog.hasClass('hide')) {
                $hideFileDialog.toggleClass('hide');
            }
        }
    });
    $('.hideFileDialog').live('click', function () {
        var $el = $(this);
        var $elContainer = $el.parent();
        if ($elContainer) {
            $elContainer.hide();
            $el.toggleClass('hide');
        }
        return false;
    });
    $('a.fileViewItem').live('click', function () {
        var $el = $(this);
        var $elContainer = $el.closest('div.b-files-tree');
        if ($elContainer) {
            var targetId = $elContainer.attr('id').replace('_container', '');
            var $targetEl = $('#' + targetId);
            if ($targetEl) {
                var targetIds = $targetEl.val().split(',');
                for (var i = 0; i < targetIds.length; i++) {
                    $targetEl = $('#' + $.trim(targetIds[i]));
                    if ($targetEl) {
                        var targetType;
                        if ($targetEl.hasClass('rel-property')) {
                            targetType = 'rel';
                        }
                        else if ($targetEl.hasClass('rev-property')) {
                            targetType = 'rev';
                        }
                        if (targetType) {
                            $targetEl.val($el.attr(targetType));
                        }
                        else {
                            $targetEl.val($el.html());
                        }
                    }
                }
                if ($elContainer) {
                    $elContainer.hide();
                }
            }
        }
        return false;
    });
}

function getFileDialogLoadUrl(dialogType) {
    var result;
    if (dialogType) {
        if (dialogType.indexOf('template') != -1) {
            result = $.cmsAdminOptions.options.fileViewOpions.templateViewUrl;
        }
        else if (dialogType.indexOf('page') != -1) {
            result = $.cmsAdminOptions.options.fileViewOpions.pageViewUrl;
        }
    }

    return result;
}

//category management
function categoryInit() {
    $('a.add-category').live('click', function () {
        setHiddenCategoryFields('', 0, $('a.add-category').attr('href'));
        togglePair('div.categories > p', 'div.categories > fieldset');
        return false;
    });
    $("a.cancel-category").live('click', function () {
        var parent = $(this);
        setHiddenCategoryFields('', 0, $('a.add-category').attr('href'));
        togglePair('div.categories > fieldset', 'div.categories > p');
        return false;
    });
    $("a.edit-category").live("click", function () {
        var $el = $(this);
        var $elText = $el.parents("tr").children("td:first");
        if ($elText) {
            var urlParts = $el.attr('href').split('/');
            setHiddenCategoryFields($elText.text(), urlParts[urlParts.length - 1], $el.attr('href'));
            togglePair('div.categories > p', 'div.categories > fieldset');
        }
        return false;
    });
    $(":input.save-category").live('click', function () {
        var $elText = $('.category-name');
        var text = $elText.val();
        if (text != "") {
            var url = $(':input.category-action-url').val();
            var categoryId = $(':input.category-id').val();
            $.post(url,
                   {
                       "id": categoryId,
                       "categoryName": text
                   })
                   .success(function (data) {
                       if (data == 1) {
                           setHiddenCategoryFields('', 0, $('a.add-category').attr('href'));
                           togglePair('div.categories > fieldset', 'div.categories > p');
                           $(".t-refresh").click();
                       }
                       else {
                           viewModel.viewEventModel.addEvent({ eventTitle: 'Error', eventBody: 'Processing error' })
                       }
                   });
        }
        return false;
    });
}
function setHiddenCategoryFields(categoryName, categoryId, categoryActionUrl) {
    $('.category-name').val(categoryName);
    $(':input.category-id').val(categoryId);
    $(':input.category-action-url').val(categoryActionUrl);
}

// tooltip
function toggleTooltip() {
    $('.b-tooltip-trigger .b-pseudo-link').live("mouseover mouseout", function (event) {
        if (event.type == "mouseover") {
            $(this).next(".b-tooltip").show();
        } else {
            $(this).next(".b-tooltip").hide();
        }
    });
}

//property management
function propertyInit() {
    $('a.add-property').live('click', function () {
        setHiddenPropertyFields('', '', $('a.add-property').attr('href'));
        togglePair('div.properties > p', 'div.properties > fieldset');
        return false;
    });
    $("a.cancel-property").live('click', function () {
        var parent = $(this);
        setHiddenPropertyFields('', '', $('a.add-property').attr('href'));
        togglePair('div.properties > fieldset', 'div.properties > p');
        return false;
    });
    $("a.edit-property").live("click", function () {
        var $el = $(this);
        var $childrenEl = $el.parents('tr').children();
        var $elText = $childrenEl.first();
        var $elValue = $childrenEl.next().first();
        if ($elText) {
            if ($elValue) {
                setHiddenPropertyFields($elText.text(), $elValue.text(), $el.attr('href'));
                togglePair('div.properties > p', 'div.properties > fieldset');
            }
        }
        return false;
    });
    $(":input.save-property").live('click', function () {
        var $elText = $('.property-name');
        var $elValue = $('.property-value');
        var text = $elText.val();
        var value = $elValue.val();
        if (text != "") {
            var url = $(':input.property-action-url').val();
            var propertyId = $(':input.property-id').val();
            $.post(url,
                   {
                       "id": propertyId,
                       "propertyName": text,
                       "propertyValue": value
                   })
                   .success(function (data) {
                       if (data == 1) {
                           setHiddenPropertyFields('', '', $('a.add-property').attr('href'));
                           togglePair('div.properties > fieldset', 'div.properties > p');
                           $(".t-refresh").click();
                       }
                       else {
                           viewModel.viewEventModel.addEvent({ eventTitle: 'Error', eventBody: 'Processing error' })
                       }
                   });
        }
        return false;
    });
}
function setHiddenPropertyFields(propertyName, propertyValue, propertyActionUrl) {
    $('.property-name').val(propertyName);
    $('.property-value').val(propertyValue);
    $(':input.property-action-url').val(propertyActionUrl);
}

//change block
function changeBlockInit() {
    $('div.change-box > a.init-change').live('click', function () {
        togglePair('div.change-box > a.init-change', 'div.change-box > div');
        return false;
    });
    $('div.change-box a.cancel-change').live('click', function () {
        togglePair('div.change-box > div', 'div.change-box > a.init-change');
        PubSub.publish($.cmsAdminEvents.registeredEvents.ClearUserChangePasswordForm);
        return false;
    });
}

//page annotations init
function pageAnnotationInit() {
    var $iframe,
    pageAnnotations,
    onIframeLoaded = function () {
        var $iframeContent = $iframe.contents(),
      	$body = $iframeContent.find("body"),
        $overlay = $("<div class='b-iframe-overlay'/>"),
        width = $iframeContent.width(),
        height = $iframeContent.height() + 200,
        iframeWindow = $iframe && $iframe[0].contentWindow,
        iframeJquery;
        try {
            $overlay.appendTo($body);
        } catch (error) {
            $(iframeWindow).load(function () {
                $overlay.appendTo($body);
            });
        }
        //        $overlay.css({
        //            position: "absolute",
        //            width: width,
        //            height: height,
        //            left: 0,
        //            top: 0,
        //            backgroundColor: "#fff",
        //            zIndex: 999,
        //            opacity: 0.7
        //        });

        if (iframeWindow) {
            iframeJquery = iframeWindow.jQuery;
        }
        if (iframeJquery) {
            iframeJquery(pageAnnotations).appendTo($body);
        }
    };

    $('a.cms-page-annotation').live('click', function () {
        var $el = $(this);
        if ($el) {
            var pageId = $el.attr('rel');
            $.get($.cmsAdminOptions.options.knownUrls.pageAnnotationsUrl + '/' + pageId)
                .success(function (data) {
                    pageAnnotations = data;
                });
            $.fancybox({
                'width': '90%',
                'height': '90%',
                'autoScale': false,
                'transitionIn': 'none',
                'transitionOut': 'none',
                'type': 'iframe',
                'href': $.cmsAdminOptions.options.knownUrls.previewPageUrl + '/' + pageId
            });
        }
        $iframe = $("#fancybox-frame");
        $iframe.load(function () {
            onIframeLoaded();
        });
        return false;
    });
}

//page preview block
function pagePreviewInit() {
    //    $('a.page-preview').live('click', function () {
    //        var $el = $(this);
    //        if ($el) {
    //            var pageId = $el.attr('rel');
    //            $.fancybox({
    //                'width': '90%',
    //                'height': '90%',
    //                'autoScale': false,
    //                'transitionIn': 'none',
    //                'transitionOut': 'none',
    //                'type': 'iframe',
    //                'href': $.cmsAdminOptions.options.knownUrls.previewPageUrl + '/' + pageId
    //            });
    //        }
    //        return false;
    //    });
}

function modulePreviewInit() {
    $('a.page-module-preview').live('click', function () {
        var $el = $(this);
        if ($el) {
            var url = $el.attr('href');
            $.fancybox({
                'width': '100%',
                'height': '100%',
                'autoScale': false,
                'transitionIn': 'none',
                'transitionOut': 'none',
                'href': url
            });
        }
        return false;
    });
}

function templatePreviewInit() {
    $('a.template-preview').live('click', function () {
        var $el = $(this);
        if ($el) {
            $.fancybox({
                'width': '100%',
                'height': '100%',
                'autoScale': false,
                'transitionIn': 'none',
                'transitionOut': 'none',
                'type': 'iframe',
                'href': $el.attr('href')
            });
        }
        return false;
    });
}

function updateTelerikEditorFor(pageControl) {
    // ensuring that telerik content editor to serializes edited data
    pageControl.each(function () {
        var editor = $(this).find(".t-editor").data("tEditor");
        if (editor !== undefined) {
            editor.update();
        }
    });
}

function changePageControlAreaState(show, $controls, reInit) {
    var $el = $('div.template-region-no-controls');
    if ($el) {
        if (show) {
            $el.show();
        }
        else {
            $el.hide();
        }
    }

    $controls.find(".b-icon_expand_min").trigger("click");

    if ($controls) {
        var index = 0;
        var $elCollection = $controls.children('div.template-region').not('.template-region-no-controls');
        var total = $elCollection.size();
        $elCollection.each(function () {
            $el = $(this);

            var $elDown = $el.find('a.b-icon_down');
            if (reInit) {
                var $elUp = $el.find('a.b-icon_up');
                if (total == 1) {
                    if (!$elUp.hasClass('hide')) {
                        $elUp.addClass('hide');
                    }
                    if (!$elDown.hasClass('hide')) {
                        $elDown.addClass('hide');
                    }
                }
                else {
                    if (index == 0) {
                        if (!$elUp.hasClass('hide')) {
                            $elUp.addClass('hide');
                        }
                        $elDown.removeClass('hide');
                    }
                    else if (index < total - 1) {
                        $elUp.removeClass('hide');
                        $elDown.removeClass('hide');
                    }
                    else if (index == total - 1) {
                        if (!$elDown.hasClass('hide')) {
                            $elDown.addClass('hide');
                        }
                        $elUp.removeClass('hide');
                    }
                }
            }
            else {
                $elDown.removeClass('hide');
            }
            index++;
        });
    }

    setPageChanged();
}

var pageChanged = false;

function setPageChanged() {
    pageChanged = true;
    // serialize state of visible page control editor
    updateTelerikEditorFor($(".page-control-body:visible"));
}

function setHoverDeleteSectionForControls($elements) {
    $($elements).each(function () {
        $(this).hover(function () {
            $(this).find('a.b-entity-delete-pagecontrol').removeClass('hide');
        }, function () {
            $(this).find('a.b-entity-delete-pagecontrol').addClass('hide');
        });
    });
}

function pageTemplateRegionInit() {
    $('#pageEdit :input:not(#TemplateRegionList)').live('change', setPageChanged);

    var previousRegion;
    $('#TemplateRegionList').live('click', function () {
        previousRegion = $('#TemplateRegionList').val();
    });
    $('#TemplateRegionList').live('change', function () {
        if (pageChanged) {
            if (!confirm("Please note that all unsaved changes in the current page region will be lost. Continue?")) {
                $('#TemplateRegionList').val(previousRegion);
                return false;
            }
        }
        var $el = $(this);
        var templateRegionId = $el.val();
        var url = window.location.href.toLowerCase();
        var newUrl;
        var isEditMode = false;
        if (url.indexOf("edit") != -1) {
            newUrl = $.cmsAdminOptions.options.knownUrls.editPageUrl;
            isEditMode = true;
        }
        else if (url.indexOf("view") != -1) {
            newUrl = $.cmsAdminOptions.options.knownUrls.viewPageUrl;
        }
        else if (url.indexOf("workflowitem") != -1) {
            newUrl = $.cmsAdminOptions.options.knownUrls.workflowViewPageUrl;
            isEditMode = true;
        }
        else {
            newUrl = url;
        }

        window.location.href =
            newUrl + '/' +
            getParametersFrom(url, isEditMode ? 1 : 2, '#') +
            '?region=' + templateRegionId;
    });

    var page;
    var region;
    var addSnippetUrl;

    $("#addPageSnippet").click(function (e) {
        e.preventDefault();
        var $link = $(this);
        page = $link.data("page");
        region = $link.data("region");
        addSnippetUrl = $link.data("url");
        $.fancybox({
            'autoDimensions': false,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'type': 'ajax',
            'href': $link.attr("href")
        });
    });

    $(document).bind("contentSelected", function (e, items) {
        $.post(addSnippetUrl, { pageId: page, templateRegionId: region, contentId: items[0] })
        .success(function (data) {
            var $collection = $('#pageControls');
            changePageControlAreaState(false, $collection);
            $collection.append(data);
            setHoverDeleteSectionForControls($collection.find('.js-control-head:last'));
        });
    });

    

    $('#addPageContent, #addContentModule').click(function () {
        var $el = $(this);
        $.post($el.attr('href'))
        .success(function (data) {
            var $collection = $('#pageControls');
            changePageControlAreaState(false, $collection);
            $collection.append(data);
            setHoverDeleteSectionForControls($collection.find('.js-control-head:last'));
        });
        return false;
    });

    $('#addPagePartialView').click(function () {
        var $el = $('#addPagePartialViewContainer');
        if ($el) {
            $el.show();
        }
        return false;
    });
    $('#addPageActionView').click(function () {
        var $el = $('#addPageActionViewContainer');
        if ($el) {
            $el.show();
        }
        return false;
    });
    $('a.addPageModule').click(function () {
        var $el = $(this);

        $el.next(".js-admin-caption").show();
        return false;
    });

    $(".js-control-title").live("click", function () {
        var $el = $(this);
        $el.hide();
        $el.closest("h3").find(".js-control-title-edit").show();
    });

    $(".js-control-title-save").live("click", function (e) {
        e.preventDefault();
        var $el = $(this).closest(".js-control-title-edit");
        $el.hide();
        var $title = $el.closest("h3").find(".js-control-title");
        $title.html($el.find("input").val());
        $title.show();
    });

    $(".js-add-page-module").click(function () {
        var $el = $(this).closest("li").find("a.addPageModule");
        var caption = $el.next(".js-admin-caption").find(".js-admin-caption-text").val();
        $.post($el.attr('href'), { caption: caption })
            .success(function (data) {
                var $collection = $('#pageControls');
                changePageControlAreaState(false, $collection);
                PubSub.publish(
                    $.cmsAdminEvents.registeredEvents.PageModuleCreated,
                    $el.attr('href'));
                $collection.append(data);
                setHoverDeleteSectionForControls($collection.find('.js-control-head:last'));
                $el.next(".js-admin-caption").hide();
                $el.next(".js-admin-caption").find(".js-admin-caption-text").val("");
            });
        return false;
    });

    $('#addPagePartialView-save').click(function () {
        var $el = $('#addPagePartialView');
        if ($el) {
            var pageIdAndTemplateRegionId = $el.attr('rel');
            $el = $('#addPagePartialViewContainer');
            if ($el) {
                var splitted = pageIdAndTemplateRegionId.split('/');
                $.post($.cmsAdminOptions.options.knownUrls.pageControlAddPartialViewUrl,
                   {
                       "pageId": splitted[0],
                       "templateRegionId": splitted[1],
                       "partialViewName": $('#PartialViewName').val(),
                       "partialAdministrationViewName": $('#PartialAdministrationViewName').val(),
                       "partialModelType": $('#PartialModelType').val(),
                       "caption": $('#ViewCaption').val()
                   })
            .success(function (data) {
                registerResetMe('partial-view-container');
                $el.hide();
                var $collection = $('#pageControls');
                changePageControlAreaState(false, $collection);
                $collection.append(data);
                setHoverDeleteSectionForControls($collection.find('.js-control-head:last'));
            });
            }
        }
        return false;
    });
    $('#addPagePartialView-cancel').click(function () {
        var $el = $('#addPagePartialViewContainer');
        if ($el) {
            registerResetMe('partial-view-container');
            $el.hide();
        }
        return false;
    });
    $('#addPageActionView-save').click(function () {
        var $el = $('#addPageActionView');
        if ($el) {
            var pageIdAndTemplateRegionId = $el.attr('rel');
            $el = $('#addPageActionViewContainer');
            if ($el) {
                var splitted = pageIdAndTemplateRegionId.split('/');
                $.post($.cmsAdminOptions.options.knownUrls.pageControlAddActionViewUrl,
                   {
                       "pageId": splitted[0],
                       "templateRegionId": splitted[1],
                       "actionController": $('#ActionController').val(),
                       "actionName": $('#ActionName').val(),
                       "partialAdministrationViewName": $('#ActionAdministrationViewName').val(),
                       "partialModelType": $('#ActionModelType').val(),
                       "caption": $('#ActionCaption').val()
                   })
            .success(function (data) {
                registerResetMe('action-view-container');
                $el.hide();
                var $collection = $('#pageControls');
                changePageControlAreaState(false, $collection);
                $collection.append(data);
                setHoverDeleteSectionForControls($collection.find('.js-control-head:last'));
            });
            }
        }
        return false;
    });
    $('#addPageActionView-cancel').click(function () {
        var $el = $('#addPageActionViewContainer');
        if ($el) {
            registerResetMe('action-view-container');
            $el.hide();
        }
        return false;
    });
    $('a.page-control-move').live('click', function () {
        $el = $(this);
        if ($el) {
            var moveUp = ($el.attr('href').indexOf('moveup', 0) >= 0);
            var $pageControl = $el.parents(".template-region");
            updateTelerikEditorFor($pageControl);
            var $siblingPageControl = (moveUp ? $pageControl.prev(".template-region") : $pageControl.next(".template-region"));
            if ($siblingPageControl) {
                if (moveUp) {
                    $siblingPageControl.before($pageControl);
                }
                else {
                    $siblingPageControl.after($pageControl);
                }
                changePageControlAreaState(false, $("#pageControls"), true);
                getTelerikEditorForFirefox($pageControl);
            }
        }
        return false;
    });

    $('#pageUrl-edit').click(function () {
        var $el = $('#PageUrl');
        var $elCancel = $('#pageUrl-cancel');
        var $elDisabled = $('div.b-text-mask-page-url');
        var $this = $(this);

        $this.val($el.val());
        var title = $this.html();
        if (title == window.adminResources.common.save) {
            title = window.adminResources.common.edit;
            $elDisabled.show();
        }
        else {
            title = window.adminResources.common.save;
            $elDisabled.hide();
        }
        $this.html(title);

        $elCancel.toggleClass('hide');
    });
    $('#pageUrl-cancel').click(function () {
        var $el = $('#PageUrl');
        var $elEdit = $('#pageUrl-edit');
        var $elDisabled = $('div.b-text-mask-page-url');

        $el.val($elEdit.val());
        $elDisabled.show();

        $elEdit.html(window.adminResources.common.edit);

        $(this).toggleClass('hide');
    });
    $('.js-title-override-link').click(function () {
        $('.js-title-override').toggleClass('hide');
    });
}

function getParameterFromId(id) {
    var idParts = id.split('-');
    return idParts[idParts.length - 1];
}

function getUrlWithoutParameter(url) {
    var result = url;
    if (url) {
        var urlParts = url.split('/');
        var url = "";
        var id;
        var index = 0;
        var len = urlParts.length - 1;
        for (var index = 0; index < len; index++) {
            url = url + urlParts[index] + '/';
        }
        result = url;
    }
    return result;
}

function getParametersFrom(url, count, removeArgs) {
    var result = url;
    if (url) {
        var urlParts = url.split('/');
        result = urlParts[urlParts.length - 1].split('?')[0];
        if (count > 1) {
            result = urlParts[urlParts.length - 2] + '/' + result;
        }
        if (removeArgs) {
            result = result.replace(/(#).*$/g, '');
        }
    }
    return result;
}

function telerikEditorPasteFromWord(e, editorId, removeFont) {
    var htmlPopup, popupTitle;
    e = $.Event(e);

    e.stopPropagation();
    e.preventDefault();

    if (removeFont) {
        popupTitle = "Paste from Word, strip font";
    } else {
        popupTitle = "Paste from Word";
    }

    var editor = $('#' + editorId + '').data('tEditor');
    if (editor) {
        if (!htmlPopup) {
            htmlPopup =
                $('<div class="html-view">' +
                    '<div><div contenteditable="true" sroll="both" id="textValue" style="width: 445px; height: 400px; overflow: auto;"></div></div>' +
                    '<div class="t-button-wrapper"><button id="htmlUpdate" class="t-button t-state-default">Insert</button>' +
                    '<button id="htmlCancel" class="t-button t-state-default">Cancel</button>' +
                    '</div>' +
                    '</div>')
                    .css('display', 'none')
                    .tWindow({
                        title: popupTitle,
                        modal: true,
                        resizable: false,
                        draggable: true,
                        width: 450,
                        onLoad: function () {
                            var $popup = $(this);
                            $popup.find('#htmlCancel')
                                    .click(function () {
                                        htmlPopup.close();
                                    })
                                    .end()
                                    .find('#htmlUpdate')
                                    .click(function () {
                                        var html = $popup.find("#textValue").html();
                                        if (removeFont) {
                                            html = html.replace(/style=("|').*?("|')/g, '').replace(/<\s*\/?\s*span\s*.*?>/g, '').replace(/<\s*\/?\s*font\s*.*?>/g, '');
                                        }
                                        editor.exec('insertHtml', { value: html });
                                        htmlPopup.close();
                                    });
                        },
                        onClose: function () {
                            editor.focus();
                        },
                        effects: $.telerik.fx.toggle.defaults()
                    })
                    .data('tWindow');
        }

        htmlPopup.center().open();
    }
}

function telerikEditorShowPlainTextBox(e, editorId) {
    var htmlPopup;
    e = $.Event(e);

    e.stopPropagation();
    e.preventDefault();
    var editor = $('#' + editorId + '').data('tEditor');
    if (editor) {
        if (!htmlPopup) {
            htmlPopup =
                $('<div class="html-view">' +
                    '<textarea id="textValue" style="width: 290px"></textarea>' +
                    '<div class="t-button-wrapper"><button id="htmlUpdate" class="t-button t-state-default">Insert</button>' +
                    '<button id="htmlCancel" class="t-button t-state-default">Cancel</button>' +
                    '</div>' +
                    '</div>')
                    .css('display', 'none')
                    .tWindow({
                        title: 'Paste as plain text',
                        modal: true,
                        resizable: false,
                        draggable: true,
                        width: 300,
                        onLoad: function () {
                            var $popup = $(this);
                            $popup.find('#htmlCancel')
                                    .click(function () {
                                        htmlPopup.close();
                                    })
                                    .end()
                                    .find('#htmlUpdate')
                                    .click(function () {
                                        var cont = $("<div />");
                                        cont.text($popup.find("#textValue").val());
                                        editor.exec('insertHtml', { value: cont.html().replace(/\n/g, '<br />') });
                                        htmlPopup.close();
                                    });
                        },
                        onClose: function () {
                            editor.focus();
                        },
                        effects: $.telerik.fx.toggle.defaults()
                    })
                    .data('tWindow');
        }

        htmlPopup.center().open();
    }
}

//telerik editor
function telerikEditorShowInsertTablePopup(e, editorId) {
    var htmlPopup;
    e = $.Event(e);

    e.stopPropagation();
    e.preventDefault();
    var editor = $('#' + editorId + '').data('tEditor');
    if (editor) {
        if (!htmlPopup) {
            htmlPopup =
                $('<div class="html-view">' +
                    '<div class="t-state-default"><ol class="b-form__rows ul-reset g-clear"><li class="b-form__row g-clear"><label for="rows">Rows:</label> <input type="text" id="rows" value="5" /></li>' +
                    '<li class="b-form__row g-clear"><label for="cols">Columns:</label> <input type="text" id="cols" value="3"/></li>' +
                    '<li class="b-form__row g-clear"><label for="headerIsRow">First row is header</label><input type="checkbox" id="headerIsRow" /></li></ol></div><br />' +
                    '<div class="t-button-wrapper">' +
                    '<button id="htmlUpdate" class="t-button t-state-default">Insert</button>' +
                    '<button id="htmlCancel" class="t-button t-state-default">Cancel</button>' +
                    '</div>' +
                    '</div>')
                    .css('display', 'none')
                    .tWindow({
                        title: 'Insert table',
                        modal: true,
                        resizable: false,
                        draggable: true,
                        width: 200,
                        onLoad: function () {
                            var $popup = $(this);
                            $popup.find('#htmlCancel')
                                    .click(function () {
                                        htmlPopup.close();
                                    })
                                    .end()
                                    .find('#htmlUpdate')
                                    .click(function () {
                                        var cols = Number($popup.find("#cols").val());
                                        var rows = Number($popup.find("#rows").val());
                                        var renderTh = $popup.find("#headerIsRow").is(":checked");
                                        var html = '<table class="t-custom-table">';
                                        for (var i = 0; i < rows; i++) {
                                            html += '<tr';
                                            if (i == 0 && renderTh) {
                                                html += " class=\"t-header-row\"";
                                            }
                                            html += ">";
                                            for (var j = 0; j < cols; j++) {
                                                html += "<td>&nbsp;</td>";
                                            }
                                            html += '</tr>';
                                        }
                                        html += "</table><p></p>";
                                        editor.exec('insertHtml', { value: html });
                                        htmlPopup.close();
                                    });
                        },
                        onClose: function () {
                            editor.focus();
                        },
                        effects: $.telerik.fx.toggle.defaults()
                    })
                    .data('tWindow');
        }

        htmlPopup.center().open();
    }
}

function telerikEditorViewSource(e, editorId) {
    var htmlSourcePopup;
    e = $.Event(e);

    e.stopPropagation();
    e.preventDefault();
    var editor = $('#' + editorId + '').data('tEditor');
    if (editor) {
        var html = editor.value();
        if (!htmlSourcePopup) {
            htmlSourcePopup =
                $('<div class="html-view">' +
                        '<div class="textarea t-state-default"><textarea></textarea></div>' +
                        '<div class="t-button-wrapper">' +
                            '<button id="htmlUpdate" class="t-button t-state-default">Update</button>' +
                            '<button id="htmlCancel" class="t-button t-state-default">Cancel</button>' +
                        '</div>' +
                    '</div>')
                .css('display', 'none')
                .tWindow({
                    title: 'View Generated HTML',
                    modal: true,
                    resizable: false,
                    draggable: true,
                    width: 700,
                    onLoad: function () {
                        var $popup = $(this);
                        $popup.find('.textarea')
                                .css('width', function () {
                                    return 700 - (this.offsetWidth - $(this).width());
                                })
                                .focus()
                                .end()
                                .find('#htmlCancel')
                                .click(function () {
                                    var $sourceView = $popup.find('textarea');
                                    htmlSourcePopup.close();
                                    $sourceView.val('');
                                })
                                .end()
                                .find('#htmlUpdate')
                                .click(function () {
                                    var $sourceView = $popup.find('textarea');
                                    var value = $sourceView.val();
                                    editor.value(value);
                                    $sourceView.val('');
                                    htmlSourcePopup.close();
                                });
                    },
                    onClose: function () {
                        editor.focus();
                    },
                    effects: $.telerik.fx.toggle.defaults()
                })
            .data('tWindow');
        }

        $(htmlSourcePopup.element).find('textarea').text(html);

        htmlSourcePopup.center().open();
    }
}

function telerikEditorExecCommand(e, editorId, command) {
    e = $.Event(e);
    e.stopPropagation();
    e.preventDefault();
    var editor = $('#' + editorId + '').data('tEditor');

    if (editor && command) {
        editor.exec(command);
    }
}

function mediaContentInit() {
    $('.b-checkbox-mediacontent-selectall').click(function () {
        var $el = $(this);
        $('.b-checkbox-mediacontent').each(function () {
            if ($el.attr('checked')) {
                $(this).attr('checked', 'checked');
            }
            else {
                $(this).removeAttr('checked');
            }
        });
    });
}

function contentCategoryInit() {
    $('.cms-js-entity-category').chosen();
}

//global events handler
var subscriber = function (msg, data) {
    switch (msg) {
        case $.cmsAdminEvents.registeredEvents.ClearUserChangePasswordForm:
            clearUserPasswordForm();
            break;
        case $.cmsAdminEvents.registeredEvents.UpdateImages:
            updateImages();
            break;
        case $.cmsAdminEvents.registeredEvents.ShowHideChildren:
            showHideChildren(data);
            break;
        default:
            break;
    }
};
PubSub.subscribe($.cmsAdminEvents.registeredEvents.ClearUserChangePasswordForm, subscriber);
PubSub.subscribe($.cmsAdminEvents.registeredEvents.UpdateImages, subscriber);
PubSub.subscribe($.cmsAdminEvents.registeredEvents.ShowHideChildren, subscriber);

function showHideChildren(data) {
    var additionalSelector = '';
    var childRegexp = /child-page-[0-9]+/g;
    var match = data.container.attr('class').match(childRegexp);
    for (var i = 0; i < match.length; i++) {
        additionalSelector += ' ' + match[i];
    }
    var $children = $('.' + data.childrenSelector + '' + data.parent);
    if (!data.isExpanded) {
        if ($children.size() == 0) {
            $.get(data.actionUrl, function (result) {
                var $result = $(result);
                $result.addClass(additionalSelector);
                data.container.after($result);
            });
        }
        else {
            var hiddenElements = [];
            $children.filter(function () {
                var $link = $(this).find('a');
                var attrRel = $link.attr('rel');
                var hasClassMax = $link.hasClass('b-icon_expand_max');

                if (attrRel !== undefined && hasClassMax) {
                    hiddenElements.push(attrRel);
                }

                if (hiddenElements.length > 0) {
                    var isHasClass = false;
                    for (var k = 0; k < hiddenElements.length; k++) {
                        if ($(this).hasClass('child-page-' + hiddenElements[k])) {
                            isHasClass = true;
                            break;
                        }
                    }
                    if (!isHasClass) {
                        return $(this);
                    }
                } else {
                    return $(this);
                }
                return null;
            }).show();

            $.post($.cmsAdminOptions.options.knownUrls.pageTreeHistoryUrl, { pageId: data.parent, isOpen: true });
        }
    }
    else {
        $children.hide();
        $.post($.cmsAdminOptions.options.knownUrls.pageTreeHistoryUrl, { pageId: data.parent, isOpen: false });
    }
}

function updateImages() {
    blocksHeight(".b-mediaFileContainer", ".b-assets-item");
}

//user -> edit -> clear password fields
function clearUserPasswordForm() {
    $('div.change-box [type="password"]').each(function () {
        $(this).val('');
    });
};

var animationQueue = [];

function addToAnimate(func) {
    animationQueue.push(func);
};

function animateInQueue() {
    if (animationQueue.length > 0) {
        var func = animationQueue.pop();
        if (func) {
            func;
            setTimeout(function () { animateInQueue(); }, 300);
        }
    }
};

function emulateTextDisabled() {
    $('.b-form__row_masked').each(
           function () {
               var $el = $(this);
               var mask = $el.find(".b-text-mask");
               var tree = $el.find(".b-files-tree");
               var text = $el.find("input[type=text]");
               var val = text.val();
               var btn = $el.find(".b-button");
               if (tree.is(":visible")) {
                   mask.hide();
               }
               else {
                   mask.show();
               }
               if (btn) {
                   btn.live('click', function () {
                       val = text.val();
                       if (val > 0) {
                           mask.hide();
                       }
                   });
               }
               tree.find("a").live('click', function () {
                   if (tree.is(":visible") || val !== "") {
                       mask.show();
                   }
               });
           }
    );
};

function blocksHeight(container, selector) {
    var $container;
    $container = $(container);
    $container.imagesLoaded(function () {
        $container.find(selector).setEqualBlocksHeight({
            count: "all"
        })
    });
}

function registerSwitchSite() {
    $(".js-switch-site").change(function () {
        var $e = $(this);
        window.location.href = $.cmsAdminOptions.options.knownUrls.switchSiteUrl + "/" + $e.val();
    });
}

function workflowDashboardInit() {
    $(".js-mass-action").live("click", function () {
        var $container = $(this).parents(".js-mass-actions-container");
        var functionName = $container.find(".js-mass-action-dropdown").val();

        if (functionName === null || functionName === "") return;

        var gridId = $container.data("grid-id");
        var $grid = $("#" + gridId);
        var items = $grid.find("input[name='itemselected']:checked");

        var data = [];
        items.each(function () {
            var $e = $(this);
            data.push({ Id: $e.val(), EntityType: $e.data("entitytype") });
        });

        if (data.length > 0) {
            executeFunctionByName(functionName, window, data);
        }
        return;
    });
}

var massActions = {
    StartWorkflow: function (data) {
        if (data.length < 5) {
            alert("At least 5 pages need to be completed to begin the approval process.");
            return;
        }

        $.ajax({
            type: 'POST',
            async: false,
            url: $.cmsAdminOptions.options.knownUrls.startWorkflowMultiUrl,
            data: JSON.stringify({ entities: data }),
            success: function () {
                location.reload();
            },
            contentType: 'application/json, charset=utf-8',
            dataType: 'json'
        });
    },

    Delete: function (data) {
        $.ajax({
            type: 'POST',
            async: false,
            url: $.cmsAdminOptions.options.knownUrls.deleteMultiUrl,
            data: JSON.stringify({ entities: data }),
            success: function () {
                location.reload();
            },
            contentType: 'application/json, charset=utf-8',
            dataType: 'json'
        });
    },

    Withdraw: function (data) {
        $.ajax({
            type: 'POST',
            async: false,
            url: $.cmsAdminOptions.options.knownUrls.withdrawMultiUrl,
            data: JSON.stringify({ entities: data }),
            success: function () {
                location.reload();
            },
            contentType: 'application/json, charset=utf-8',
            dataType: 'json'
        });
    }
};

function searchSnippetInit() {
    $(document).ready(function () {
        if ($("#SearchAreas").data("checklistinitialized") !== "true") {
            $("#SearchAreas").data("checklistinitialized", "true");
            $("#SearchAreas").dropdownchecklist({
                icon: { placement: 'right' },
                width: 20,
                maxDropHeight: 250,
                firstItemChecksAll: 'exclusive',
                emptyText: "Please select",
                onItemClick: function (checkbox, selector) {
                    var justChecked = checkbox.prop("checked");
                    var checkCount = (justChecked) ? 1 : -1;
                    for (var i = 0; i < selector.options.length; i++) {
                        if (selector.options[i].selected) checkCount += 1;
                    }
                    if (checkCount == 0)
                        selector.options[0].prop("checked", true);
                }
            });
        }
    });
}

function initDraggable(sel) {
    $(sel).each(function () {
        var $el = $(this);
        $el.attr("draggable", true);
        $el.bind("dragstart", function (e) {
            e.originalEvent.dataTransfer.effectAllowed = 'move';
            e.originalEvent.dataTransfer.setData("Text", $el.data("id"));
            e.originalEvent.dataTransfer.setData("Action", $el.data("type"));
        });
    });
}

function registerPageEdit() {
    $(document).ready(function () {
        //page preview
        var isPreview;
        var isApply;
        var $pageForm = $('#pageEdit');
        $('#Workflow').fancybox({
            content: '#cms-js-send-for-approval',
            type: 'inline',
            autoScale: false,
            autoDimensions: true
        });

        $('#cms-js-workflow-cancel').click(function () {
            $.fancybox.close();
        });

        $('#cms-js-workflow-submit').click(function () {
            var formParameters = $pageForm.formSerialize();
            var formElements = $('#cms-js-send-for-approval').find(":input");
            var workflowParameters = formElements.serialize();
            $.post($pageForm.attr('action'), formParameters + '&Workflow=Workflow&' + workflowParameters)
                    .success(function (data) {
                        $.fancybox.close();
                    })
                    .error(function () {
                        $.fancybox.close();
                    });
        });

        $pageForm.ajaxForm(
            {
                beforeSubmit: function (formData) {
                    isPreview = $.param(formData).indexOf('Preview=Preview') != -1;
                    isApply = $.param(formData).indexOf('Apply=Save') != -1;
                    return true;
                },
                success: function (responseText) {
                    var viewPortWidth = '100%', viewPortHeight = $(window).height(),
                    $ifrm = $('#previewIfr');
                    if (isPreview) {
                        $.fancybox({
                            'width': '90%',
                            'height': '90%',
                            'autoScale': false,
                            'transitionIn': 'none',
                            'transitionOut': 'none',
                            'type': 'inline',
                            'href': '#previewIfr',
                            'autoDimensions': false
                        });
                        $ifrm.css("visibility", "hidden").attr('width', viewPortWidth).attr('height', viewPortHeight);
                        ifrm = ($ifrm[0].contentWindow) ? $ifrm[0].contentWindow : ($ifrm[0].contentDocument.document) ? $ifrm[0].contentDocument.document : $ifrm[0].contentDocument;
                        ifrm.document.open();
                        ifrm.document.write(responseText);
                        ifrm.document.close();

                        setTimeout(function () {
                            var contentHeight = $ifrm.contents().find(".container").height();
                            if (contentHeight !== null) {
                                $ifrm.attr('height', contentHeight);
                            }
                            $ifrm.css("visibility", "visible");
                        }, 2000);
                    }
                    else {
                        // TODO: just show notification - form was saved
                        if (isApply) {
                            window.location.href = responseText;
                        } else {
                            window.location.href = $.cmsAdminOptions.options.knownUrls.pageIndexUrl;
                        }
                    }
                }
            });
        $("#pageControls").sortable({
            handle: ".b-form__head",
            revert: true,
            cursor: 'move',
            placeholder: "ui-state-highlight",
            start: function (e, ui) {
                updateTelerikEditorFor(ui.item);
            },
            stop: function (e, ui) {
                getTelerikEditorForFirefox(ui.item);
            }
        });
    });
}

function initPagesFilter() {
    $form = $("#pageFilter");
    $(".js-page-filter a").click(function () {
        $el = $(this);
        $form.find("#IsPublished").val($el.data("val"));
        $form.submit();
        return false;
    });
}
function initSetPassword() {
    var setPasswordCheckbox = $('.js-set-password-checkbox');
    var invert, value;
    if (setPasswordCheckbox.length > 0) {
        invert = !!(setPasswordCheckbox.data("invert"));
        value = !!(setPasswordCheckbox.prop('checked'));
        showOrHidePasswordSection(invert ? !value : value);
    }

    $('.js-set-password-checkbox').change(function () {
        value = !!($(this).prop('checked'));
        showOrHidePasswordSection(invert ? !value : value);
    });
}

function showOrHidePasswordSection(value) {
    var sections = $('.js-password-section');
    if (sections.length > 0) {
        if (value) {
            sections.addClass('hide');
        } else {
            sections.removeClass('hide');
        }
    }
}
function initMetas() {
    $(".js-values-source").change(function () {
        $.post($(this).data("url"), { name: $(this).val() }, function (data) {
            if (data != 0) {
                $(".js-custom-values").html(data);
            }
            else {
                $(".js-custom-values").html("");
            }
        });
    });

    $(".js-add-new-value-link").click(function (e) {
        e.preventDefault();
        $(this).closest(".js-new-meta-container").find(".js-new-meta-controls").show();
        $(this).hide();
    });
    $(".js-add-new-meta-value").click(function () {
        var $el = $(this);
        var con = $el.closest(".js-new-meta-container");
        $.post($el.data("url"), { linkid: $el.data("linkid"), value: con.find(".js-new-meta-value").val() }, function (data) {
            con.find(".js-new-meta-controls").hide();
            con.find(".js-add-new-value-link").show();
            var sel = $($el.data("select"));
            sel.append('<option value="' + data.Value + '">' + data.Text + '</option>');
            sel.val(data.Value);
        });
    });
    $(".js-cancel-new-meta-value").click(function () {
        var con = $(this).closest(".js-new-meta-container");
        con.find(".js-new-meta-controls").hide();
        con.find(".js-add-new-value-link").show();
    });
}

function initCommonFancyBox() {
    $(".js-common-fancy").fancybox({
        'width': '100%',
        'height': '100%',
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        type: 'ajax'
    });
}

function initReconnect() {
    window.status = 'Link to server refreshed';
    var img = new Image();
    img.src = $.cmsAdminOptions.options.knownUrls.reconnectUrl;
    //window.setTimeout(initReconnect(), 30000);
}

function getTelerikEditorForFirefox($pageControl) {
    if (BrowserDetect.browser === 'Firefox') {
        var editor = $pageControl.find('table[id^=contentEditor]').data('tEditor');
        if (editor) {
            var id = editor.element.id;
            var clientId = id.slice(id.indexOf('_') + 1);

            var data = {
                clientId: clientId,
                name: editor.textarea.name,
                content: editor.value()
            };

            $.post($.cmsAdminOptions.options.knownUrls.getTelerikEditor, data)
                .success(function (result) {
                    $pageControl.find('table[id=' + id + ']').replaceWith($(result));
                });
        }
    }
}